<template>
  <div id="dfset" class="template-page">
    <div class="tree-table">
      <el-tree :expand-on-click-node="false" ref="dataTree" :default-expand-all="true" :data="typeList" :props="defaultProps" node-key="id" highlight-current
        @node-click="handleClickType" class="tools-tree" v-loading="tloading">
        <template #default="{ data }">
          <span>{{ data.name }}</span>
          <span>
            <el-button v-if="data.id === null" type="success" class="addCirBtn" size="small" icon="Plus" circle @click="appendType()"></el-button>
            <template v-else>
              <el-button type="warning" class="cirBtn" size="small" icon="EditPen" circle @click="handleEditType(data)"></el-button>
              <el-button type="info" class="cirBtn" size="small" icon="Delete" circle @click="removeType(data.id)"></el-button>
            </template>
          </span>
        </template>
      </el-tree>
      <el-dialog title="保存分类" :show-close="false" v-model="showTypeDialog" :close-on-click-modal="false" width="600px">
        <el-form ref="treeFormRef" label-width="110px" :model="treeForm" :rules="formRule" :inline-message="true" class="tree-dia">
          <el-form-item prop="name" label="分类名称">
            <el-input v-model="treeForm.name" type="text" placeholder="请输入分类名称"></el-input>
          </el-form-item>
          <el-form-item prop="code" label="编码">
            <el-input type="text" v-model="treeForm.code" placeholder="请输入编码"></el-input>
          </el-form-item>
          <el-form-item prop="order" label="顺序号">
            <el-input type="text" v-model="treeForm.order" placeholder="请输入顺序号"></el-input>
          </el-form-item>
        </el-form>
        <template #footer>
          <el-button type="primary" @click="saveType(treeFormRef)">保 存</el-button>
          <el-button @click="closeTypeDialog(treeFormRef)">取 消</el-button>
        </template>
      </el-dialog>
      <div class="tools">
        <el-divider content-position="left">{{ sltTypeNode.name }}</el-divider>
        <el-button class="addAdvBtn" type="primary" @click="addDict()">新建字典</el-button>
        <el-table v-loading="loading" row-key="id" :data="dictItemList" :tree-props="{ children: 'children' }" :max-height="conHeight">
          <el-table-column prop="code" label="编码" width="180" align="left"></el-table-column>
          <el-table-column prop="name" label="名称" align="left">
            <template #default="scope">
              <el-link type="primary" :underline="false" @click="handleEditDict(scope.row)">{{ scope.row.name }}</el-link>
            </template>
          </el-table-column>
          <el-table-column prop="shortCode" label="拼音简码" width="150" align="center"></el-table-column>
          <el-table-column prop="status" label="状态" width="90" align="center">
            <template #default="scope">
              <span>{{ formatStatus(scope.row.status) }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="order" label="顺序号" width="80" align="center"></el-table-column>
          <el-table-column label="操作" align="center">
            <template #default="scope">
              <el-button size="small" type="primary" icon="EditPen" plain circle @click="handleEditDict(scope.row)"></el-button>
              <el-button size="small" type="danger" icon="Delete" plain circle @click="handleDeleteDict(scope.row.id)"></el-button>
              <el-button size="small" type="primary" icon="CirclePlus" plain circle @click="handleAddChild(scope.row)"></el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-pagination :background="true" @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="pageIndex" :page-sizes="pageSizeList"
          :page-size="pageSize" layout="total, sizes, prev, pager, next, jumper" :total="totalCount"></el-pagination>
      </div>
      <el-dialog title="字典维护" :show-close="false" v-model="showDictDialog" :close-on-click-modal="false" @close="closeDictDialog(dictFormRef)" width="600px">
        <el-form ref="dictFormRef" label-width="110px" :model="dictForm" :rules="formRule" :inline-message="true" class="form-input-m">
          <el-form-item label="所属分类">
            <el-input type="text" v-model="sltTypeNode.name" disabled></el-input>
          </el-form-item>
          <el-form-item prop="name" label="名称">
            <el-input type="text" v-model="dictForm.name" placeholder="请输入名称"></el-input>
          </el-form-item>
          <el-form-item prop="code" label="编码">
            <el-input type="text" v-model="dictForm.code" placeholder="请输入编码"></el-input>
          </el-form-item>
          <el-form-item label="拼音简码">
            <el-input type="text" v-model="dictForm.shortCode" placeholder="请输入拼音简码"></el-input>
          </el-form-item>
          <el-form-item label="状态">
            <el-radio-group v-model="dictForm.status">
              <el-radio :label="1">启用</el-radio>
              <el-radio :label="2">禁用</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="顺序号">
            <el-input type="text" v-model="dictForm.order" placeholder="请输入顺序号"></el-input>
          </el-form-item>
        </el-form>
        <template #footer>
          <el-button type="primary" class="addBtn" @click="saveDict(dictFormRef)">保 存</el-button>
          <el-button @click="closeDictDialog(dictFormRef)">取 消</el-button>
        </template>
      </el-dialog>
    </div>
  </div>
</template>
<script setup lang="ts">
import { ref, reactive, getCurrentInstance, nextTick } from 'vue';
import { pageSizes, notifyType, notifyMessage } from '../../utils/common';
import type { ElTree, FormInstance } from 'element-plus';
import { AppStore } from '../../stores/store';
let conHeight = ref(
  (document.documentElement.clientHeight || document.body.clientHeight) - 160 + 'px'
);
let { proxy }: any = getCurrentInstance();
let store = AppStore();
let dataTree = ref<InstanceType<typeof ElTree>>();
let treeFormRef = ref<FormInstance>();
let dictFormRef = ref<FormInstance>();
let pageSizeList = ref(pageSizes);
let pageSize = ref(pageSizes[0]);
let pageIndex = ref(1);
let totalCount = ref(0);
let loading = ref(false);
let tloading = ref(false);
// 字典分类表单treeForm
let treeForm = reactive({
  id: '',
  orgId: store.userInfo.orgId,
  name: '', //食源性字典名称
  code: '', //字典分类编码
  order: '' //顺序号
});
// 字典表单dictForm
let dictForm = reactive({
  id: '',
  orgId: store.userInfo.orgId,
  roles: [],
  name: '', //名称
  code: '', //编码
  typeId: '', //所属分类id
  shortCode: '', //拼音简码
  standardCode: '', //国家编码
  order: '',
  status: 1, //状态, 启用1，禁用2
  parentId: null
});
//字典类型标题
let sltTypeNode = reactive({
  id: '',
  name: '字典类型',
  code: ''
});
//字典分类表单和字典维护表单校验
let formRule = {
  name: [
    {
      required: true,
      message: '请输入名称',
      trigger: 'blur'
    },
    {
      min: 2,
      max: 50,
      message: '长度在2到8个字符',
      trigger: 'blur'
    }
  ],
  code: [
    {
      required: true,
      message: '请输入编码',
      trigger: 'blur'
    }
  ]
};

// 字典分类弹框
let showTypeDialog = ref(false);
// 添加字典弹框
let showDictDialog = ref(false);
// 分类项列表
let typeList: any = reactive([
  {
    id: null,
    name: '字典分类',
    children: []
  }
]);
let defaultProps = {
  children: 'children',
  label: 'name'
};
// 字典列表数组数据
let dictItemList: any = reactive([]);

findDictTreeTypeList();

// 获取字典分类数据
function findDictTreeTypeList() {
  tloading.value = true;
  const url = '/api/sys/findDictReportFieldList';
  proxy.$http
    .get(url, { params: { orgId: store.userInfo.orgId } })
    .then((res: any) => {
      if (res.status.code !== 1) {
        notifyMessage(res.status.msg, notifyType.warning, proxy);
      } else {
        // 获取到的数据分配给前端字典分类列表数组
        typeList[0].children = res.data.fieldList;
        if (typeList[0].children.length > 0) {
          sltTypeNode.id = typeList[0].children[0].id;
          sltTypeNode.code = typeList[0].children[0].code;
          sltTypeNode.name = typeList[0].children[0].name;
          // 光标定位在字典分类列表的第一项
          setCurTypeNode(typeList[0].children[0].id);
          // 分类列表数据获取完成后获取建议列表的数据
          findDictTreeItemList();
        } else {
          dictItemList = [];
          sltTypeNode.id = '';
          sltTypeNode.name = '字典类型';
          sltTypeNode.code = '';
        }
      }
      tloading.value = false;
    })
    .catch((err: string) => {
      tloading.value = false;
      notifyMessage(err, notifyType.warning, proxy);
    });
}

function formatStatus(status: any) {
  switch (status) {
    case 1:
      return '启用';
    case 2:
      return '禁用';
    default:
      return '';
  }
}

// 光标定位在指定字典分类上
function setCurTypeNode(nodeId: any) {
  nextTick(() => {
    dataTree.value!.setCurrentKey(nodeId);
  });
}

// 显示添加分类项弹框
function appendType() {
  treeForm.id = '';
  treeForm.order = typeList[0].children.length + 1;
  showTypeDialog.value = true;
}
// 编辑分类项弹框
function handleEditType(data: any) {
  treeForm.id = data.id;
  treeForm.name = data.name;
  treeForm.code = data.code;
  treeForm.order = data.order;
  showTypeDialog.value = true;
}

// 保存添加或编辑后的数据
function saveType(treeFormRef: any) {
  if (!treeFormRef) return;
  treeFormRef.validate((valid: any) => {
    if (!valid) {
      return false;
    }
    // 请求的数据储存的对象
    const obj = {
      id: treeForm.id,
      orgId: treeForm.orgId,
      name: treeForm.name,
      code: treeForm.code,
      order: treeForm.order
      // type: $route.query.type//业务类型
    };
    let url = '';
    if (treeForm.id) {
      url = '/api/sys/editDictReportField';
    } else {
      url = '/api/sys/addDictReportField';
    }
    proxy.$http
      .post(url, obj)
      .then((res: any) => {
        if (res.status.code === 1) {
          notifyMessage('保存成功', notifyType.success, proxy);
          showTypeDialog.value = false;
          if (treeForm.id) {
            // 编辑保存
            const curNode = dataTree.value!.getCurrentNode();
            curNode.name = treeForm.name;
            curNode.code = treeForm.code;
            sltTypeNode.id = treeForm.id;
            sltTypeNode.code = treeForm.code;
            sltTypeNode.name = treeForm.name;
          } else {
            // 添加保存
            const temp = {
              id: res.data.typeId,
              name: treeForm.name,
              code: treeForm.code,
              order: treeForm.order
            };
            // 数据对象放在temp对象内添加到数组 页面数据更新
            typeList[0].children.push(temp);
            setCurTypeNode(temp.id);
            sltTypeNode.id = temp.id;
            sltTypeNode.code = temp.code;
            sltTypeNode.name = temp.name;
            findDictTreeItemList();
          }
          // 保存后清空表单数据
          clearTreeForm();
        } else {
          notifyMessage(res.status.msg, notifyType.warning, proxy);
        }
      })
      .catch((err: string) => {
        notifyMessage(err, notifyType.warning, proxy);
      });
    return true;
  });
}

// 关闭分类弹框
function closeTypeDialog(treeFormRef: any) {
  treeFormRef.resetFields();
  clearTreeForm();
  showTypeDialog.value = false;
}
// 清空treeForm表单
function clearTreeForm() {
  treeForm.id = '';
  treeForm.name = '';
  treeForm.code = '';
  treeForm.order = '';
}

// 删除字典分类项数据
function removeType(id: string) {
  proxy
    .$confirm('确定删除此分类？注意：字典分类下字典数据，也会全部删除！', '提示', {
      cancelButtonClass: 'cancel-button',
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    .then(() => {
      const url = '/api/sys/deleteDictReportField';
      proxy.$http
        .post(url, { id })
        .then((res: any) => {
          if (res.status.code === 1) {
            notifyMessage('删除成功', notifyType.success, proxy);
            // 删除成功光标定位到分类第一项，显示第一项数据
            findDictTreeTypeList();
            if (typeList[0].children.length > 0) {
              setCurTypeNode(typeList[0].children[0].id);
            }
          } else {
            notifyMessage(res.status.msg, notifyType.warning, proxy);
          }
        })
        .catch((err: string) => {
          notifyMessage(err, notifyType.warning, proxy);
        });
    })
    .catch((err: string) => {
      console.log(err);
    });
}
// 获取对应分类项下字典数据
function findDictTreeItemList() {
  loading.value = true;
  dictItemList.length = 0;
  const url = '/api/sys/findDictReportValueList';
  // 将标题的id给列表获取数据用到的的typeId
  proxy.$http
    .get(url, {
      params: { typeId: sltTypeNode.id, pageSize: pageSize.value, pageIndex: pageIndex.value }
    })
    .then((res: any) => {
      if (res.status.code !== 1) {
        notifyMessage(res.status.msg, notifyType.warning, proxy);
      } else {
        dictItemList.push(...res.data.itemList);
        totalCount.value = res.data.count;
      }
      loading.value = false;
    })
    .catch((err: string) => {
      loading.value = false;
      notifyMessage(err, notifyType.warning, proxy);
    });
}

// 点击字典分类项
function handleClickType(obj: any) {
  if (obj.id === null) {
    return;
  }
  sltTypeNode.id = obj.id;
  sltTypeNode.code = obj.code;
  sltTypeNode.name = obj.name;
  pageIndex.value = 1;
  findDictTreeItemList();
}

// 显示添加字典弹框
function addDict() {
  if (!sltTypeNode.id) {
    notifyMessage('请先添加分类', notifyType.warning, proxy);
    return;
  }
  dictForm.typeId = sltTypeNode.id;
  dictForm.parentId = null;
  dictForm.order = (totalCount.value + 1).toString();
  showDictDialog.value = true;
}

// 显示编辑字典时弹框
function handleEditDict(row: any) {
  dictForm.id = row.id;
  dictForm.typeId = row.typeId;
  dictForm.name = row.name;
  dictForm.code = row.code;
  dictForm.shortCode = row.shortCode;
  dictForm.standardCode = row.standardCode;
  dictForm.status = row.status;
  dictForm.order = row.order;
  dictForm.parentId = row.parentId;
  showDictDialog.value = true;
}

// 保存添加或建议数据
function saveDict(dictFormRef: any) {
  if (!dictFormRef) return;
  dictFormRef.validate((valid: any) => {
    if (!valid) {
      return false;
    }
    // 请求数据的对象
    const obj = {
      id: dictForm.id,
      typeId: dictForm.typeId,
      orgId: treeForm.orgId,
      name: dictForm.name,
      code: dictForm.code,
      shortCode: dictForm.shortCode,
      standardCode: dictForm.standardCode,
      status: dictForm.status,
      order: dictForm.order,
      parentId: dictForm.parentId,
      roles: dictForm.roles
    };
    let url = '';
    // 判断添加和编辑接口
    if (dictForm.id) {
      url = '/api/sys/editDictReportValue';
    } else {
      url = '/api/sys/addDictReportValue';
    }
    proxy.$http
      .post(url, obj)
      .then((res: any) => {
        if (res.status.code === 1) {
          notifyMessage('保存成功', notifyType.success, proxy);
          showDictDialog.value = false;
          // 列表数据显示第一页
          pageIndex.value = 1;
          // 获取建议列表数据
          findDictTreeItemList();
          // 清空表单
          clearDictForm();
        } else {
          notifyMessage(res.status.msg, notifyType.warning, proxy);
        }
      })
      .catch((err: string) => {
        notifyMessage(err, notifyType.warning, proxy);
      });
    return true;
  });
}

// 关闭添加诊断弹框
function closeDictDialog(dictFormRef: any) {
  dictFormRef.resetFields();
  clearDictForm();
  showDictDialog.value = false;
}

// 清空表单方法
function clearDictForm() {
  dictForm.id = '';
  dictForm.typeId = '';
  dictForm.name = '';
  dictForm.code = '';
  dictForm.shortCode = '';
  dictForm.standardCode = '';
  dictForm.status = 1;
  dictForm.order = '';
  dictForm.roles = [];
  dictForm.parentId = null;
}

//删除字典数据
function handleDeleteDict(id: string) {
  proxy
    .$confirm('确定删除此字典?', '提示', {
      cancelButtonClass: 'cancel-button',
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    .then(() => {
      const url = '/api/sys/deleteDictReportValue';
      proxy.$http
        .post(url, { id })
        .then((res: any) => {
          if (res.status.code === 1) {
            notifyMessage('删除成功', notifyType.success, proxy);
            // 重新请求列表数据
            findDictTreeItemList();
          } else {
            notifyMessage(res.status.msg, notifyType.warning, proxy);
          }
        })
        .catch((err: string) => {
          notifyMessage(err, notifyType.warning, proxy);
        });
    })
    .catch((err: string) => {
      console.log(err);
    });
}

// 添加子级项目
function handleAddChild(row: any) {
  dictForm.parentId = row.id;
  dictForm.typeId = sltTypeNode.id;
  dictForm.order = row.children ? row.children.length + 1 : 1;
  showDictDialog.value = true;
}

//点击每页数量
function handleSizeChange(val: any) {
  pageSize.value = val;
  pageIndex.value = 1;
  findDictTreeItemList();
}

//点击跳转页码
function handleCurrentChange(val: any) {
  pageIndex.value = val;
  findDictTreeItemList();
}
</script>
<style lang="scss">
#dfset {
  .tree-table {
    display: flex;
    min-height: 400px;
    .tools-tree {
      width: 15%;
      min-width: 150px;
      margin: 0;
      padding: 5px;
      font-size: $font-size;
      border: none;
      .addCirBtn {
        width: 18px;
        height: 18px;
        padding: 0px;
        margin-left: 10px;
      }
      .cirBtn {
        display: none;
        width: 16px;
        height: 16px;
        padding: 0px;
        margin-left: 10px;
      }
      .el-tree-node__content:hover {
        .cirBtn {
          display: inline-block !important;
        }
      }
    }
    .tree-dia {
      .el-input {
        width: 45%;
      }
      .el-input__inner {
        width: 200px;
      }
    }
    .tools {
      width: 85%;
      margin: 0 0 0 1px;
      .el-divider {
        width: 100%;
      }
      .el-divider--horizontal {
        margin: 7px 0 20px 0;
      }
      .addAdvBtn {
        margin-bottom: 10px;
      }
      .el-divider__text {
        font-size: $font-size;
      }
      .el-dialog__body {
        padding-top: 20px;
      }
      .divider {
        width: 310px;
        .el-divider__text {
          font-weight: bold;
          font-size: $font-size;
        }
      }
    }
  }
  .el-pagination {
    margin-top: 10px;
  }
}
</style>